package raft

import (
	"hundsun.com/hsl/hschain/consensus/common"
	"hundsun.com/hsl/hschain/consensus/impl/raft/checker"
	solominer "hundsun.com/hsl/hschain/consensus/impl/raft/miner"
	"hundsun.com/hsl/hschain/consensus/impl/raft/selector"
	"hundsun.com/hsl/hschain/consensus/types"
	"hundsun.com/hsl/hschain/module"
	"hundsun.com/hsl/hschain/module/registry"
)

func init() {
	common.RegConsensus(types.ConsensusTypeRaft, NewRaft)
}

// Module raft module
type Module struct {
	module.Adapter
	types.ConsensusStatus

	selector *selector.RaftSelector
	miner    *solominer.RaftMiner
	checker  *checker.RaftChecker

	baseClient *common.BaseClient
}

// NewRaft 新建一个Raft共识节点
func NewRaft() common.ConsensusModule {
	m := &Module{}
	m.baseClient = common.NewBaseClient()
	m.selector = selector.NewSelector()
	m.miner = solominer.NewMiner(m.GetBaseClient())
	m.checker = checker.NewChecker(m.GetBaseClient())
	moduleStartupFunc := func(startedInterestedModules map[string][]*registry.ModRegKV) error {
		m.selector.Start(m.RootCtx, m.Config, m.Log)
		m.miner.Start(m.RootCtx, m.Config, m.Log)
		m.checker.Start(m.RootCtx, m.Config, m.Log)
		return nil
	}
	m.Init(module.ConsensusModuleName, []string{module.P2pModuleName}, moduleStartupFunc)
	return m
}

// GetBaseClient get base client
func (m *Module) GetBaseClient() *common.BaseClient {
	return m.baseClient
}

// SetBaseClient set base client
func (m *Module) SetBaseClient(client *common.BaseClient) {
	m.baseClient = client
}
